<?php

namespace app\xwam\controller;

/**
 * 文件上传控制器
 *
 * @version 1.0 2014-11-7 by sutroon
 * @version 1.1 2018-1-24 sochishun 重构
 */
class Uploader extends AppbaseController {

    function demo(){
        return '<form method="post" action="'. url('kindeditor_upload').'" enctype="multipart/form-data"><input type="file" name="file1" /><button type="submit">Upload</button></form>';
    }
    /**
     * 单文件上传表单
     * @param string $name 文件域输入框名称
     * @param string $callback JS回调函数名称
     * @param string $debug 是否调试
     * @param string scene 文件上传场景(zip或image)
     * @param string param 参数
     * @version 2017-1-6
     * @version 2018-1-31 sochishun 新增$param和$scene选项参数
     */
    function single_file($name = '', $callback = 'single_uploader_cb', $debug = 'N', $scene = 'image', $param = '') {
        return view('', array('name' => $name, 'callback' => $callback, 'debug' => $debug, 'param' => $param, 'scene' => $scene));
    }

    /**
     * 文件批量上传表单
     * @param type $name
     * @param type $callback
     * @param type $debug
     * @return type
     * @version 2017-1-6
     */
    function multi_file($name = '', $callback = 'multi_uploader_cb', $debug = 'N') {
        return view('', array('name' => $name, 'callback' => $callback, 'debug' => $debug));
    }

    /**
     * 从磁盘删除指定的文件
     * @param string $filepath
     * @version 2017-1-6 Added.
     * @version 2018-1-24 增加文件判断和错误提示
     */
    function delete($filepath = '') {
        $result = true;
        $info = '';
        if ($filepath) {
            $filepath = env('root_path') . str_replace('/', DS, $filepath); // is_file()和unlink都要本地路径(相对路径或绝对路径)
            if (!is_file($filepath)) {
                $result = false;
                $info = '文件不存在!';
            }
        } else {
            $result = false;
            $info = '文件路径为空!';
        }
        if ($result) {
            try {
                $result = unlink($filepath);
            } catch (\Exception $ex) {
                $info = $ex->getMessage();
            }
        }
        return json_encode(array('status' => $result, 'info' => $info));
    }

    /**
     * kindeditor编辑器上传处理
     * <br />512000=500KB
     * <br />2097152=2MB
     * @param string $category 分类
     * @param boolean|array $exdb 是否保存到数据库(若为数组则表示附加到数据库的扩展数据)
     * @version 1.0 2014-11-7 sutroon Added.
     * @version 2.0 2015-3-28 SoChishun 重构.
     * @version 2.1 2015-7-16 SoChishun 重构.
     * @version 2.2 2018-1-23 SoChishun 支持TP5方法
     * @version 2.3 2018-1-31 sochishun 新增$scene和$param参数
     */
    public function kindeditor_upload($scene = '', $param = '') {
        switch ($scene) {
            case 'doc':
                $option = ['size' => '1MB', 'ext' => 'doc,docx,xls,xlsx,ppt,pptx,txt,rtf,wps,et'];
                break;
            case 'zip':
                $option = ['size' => '10MB', 'ext' => 'zip,rar'];
                break;
            default:
                $option = ['size' => '150KB', 'ext' => 'jpg,png,gif'];
                break;
        }
        $field = '';
        $upresult = $this->uploadFile($field, $option);
        if ($upresult['status']) {
            $result = array('error' => 0, 'url' => '/public/uploads/' . str_replace(DS, '/', $upresult['info']->getSaveName()));
        } else {
            $result = array('error' => 1, 'message' => $upresult['info']);
        }
        return json_encode($result);
    }

    /**
     * 单个文件上传操作
     * @return array
     * @version 2018-1-23
     */
    function uploadFile($field = '', $option = []) {
        $result = $this->uploadFiles($field, $option);
        if ($result) {
            return current($result);
        }
        return array('status' => false, 'info' => '没有文件');
    }

    /**
     * 批量文件上传操作
     * @param string $field
     * @param array $option
     * @return array
     * @version 2018-1-23
     */
    function uploadFiles($field = '', $option = []) {
        $default = ['size' => '150KB', 'ext' => 'jpg,png,gif'];
        if ($option) {
            $default = array_merge($default, $option);
        } else if (is_null($option)) {
            $default = false;
        }
        if ($default && strpos($default['size'], 'B')) {
            $default['size'] = format_to_bytes($default['size']);
        }
        $outresult = [];
        // 获取表单上传文件
        /*
          'error' => '',
          'filename' => 'E:\\pdc\\projectenv\\altifrm_with_tp5\\public\\uploads\\20180123\\4e25d95ba1c63782a0e902e85f845626.png',
          'saveName' => '20180123\\4e25d95ba1c63782a0e902e85f845626.png',
          'rule' => 'date',
          'info' => ['name' => 'yintao.png', 'type' => 'image/png', 'tmp_name' => 'C:\\Windows\\php61A7.tmp', 'error' => 0, 'size' => 3565]
         * =======         
          echo $info->getExtension(); // 输出 jpg
          echo $info->getFilename(); // 输出 42a79759f284b767dfcb2a0197904287.jpg
          echo $info->getSaveName(); // 输出 20180123\\42a79759f284b767dfcb2a0197904287.jpg
         */
        $files = request()->file($field);
        if (!$files) {
            return array(array('status' => false, 'info' => '上传异常!'));
        }
        foreach ($files as $file) {
            // 移动到框架应用根目录/public/uploads/ 目录下
            if ($default) {
                $file->validate($default);
            }
            $info = $file->move(env('root_path') . 'public' . DS . 'uploads');
            if ($info) {
                // 成功上传后 获取上传信息
                $outresult[] = array('status' => true, 'info' => $info);
            } else {
                // 上传失败获取错误信息
                $outresult[] = array('status' => false, 'info' => $file->getError());
            }
        }
        return $outresult;
    }

}
